package com.yaowk.sfp.system.server.service.impl;

import com.yaowk.sfp.system.api.model.Menu;
import com.yaowk.sfp.system.server.dao.ResourceDao;
import com.yaowk.sfp.system.server.dao.RoleDao;
import com.yaowk.sfp.system.server.dao.UserDao;
import com.yaowk.sfp.system.server.entity.SysMenu;
import com.yaowk.sfp.system.server.entity.SysResource;
import com.yaowk.sfp.system.server.entity.SysRole;
import com.yaowk.sfp.system.server.entity.SysUser;
import com.yaowk.sfp.system.server.service.base.MenuServiceBase;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class MenuServiceImpl extends MenuServiceBase {

    @Autowired
    private RoleDao roleDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private ResourceDao resourceDao;

    @Override
    @Transactional
    public List<Menu> findAllByRoleId(Long roleId) {
        SysRole sysRole = roleDao.findOne(roleId);
        return entity2Model(sysRole.getMenus());
    }

    @Override
    @Transactional
    public List<Menu> findAllByUserId(Long userId) {
        List<SysMenu> sysMenus = new ArrayList<>();
        SysUser sysUser = userDao.findOne(userId);
        Set<SysRole> sysRoles = sysUser.getRoles();
        for (SysRole sysRole : sysRoles) {
            sysMenus.addAll(sysRole.getMenus());
        }
        return entity2Model(sysMenus);
    }

    @Override
    @Transactional
    public void editResource(Long menuId, List<Long> resourceId) {
        SysMenu sysMenu = getDao().findOne(menuId);
        Set<SysResource> resources = new HashSet<>();
        sysMenu.setResources(resources);
        for (Long id : resourceId) {
            resources.add(resourceDao.findOne(id));
        }
        getDao().save(sysMenu);
    }
}